import React from 'react';

import { ReactComponent as Check } from '@/assets/images/auth/Check.svg';
import { ReactComponent as ChevronLeft } from '@/assets/images/auth/ChevronLeft.svg';
import { ReactComponent as ChevronRight } from '@/assets/images/auth/ChevronRight.svg';
import { ReactComponent as CloseCircleMobile } from '@/assets/images/auth/CloseMobileSmall.svg';
import { Container, TitleBlock } from '@/entities/auth';
import { clearEmailStatus, clearFeedbackFiles } from '@/entities/auth/model/actions';
import { getFeedbackFiles } from '@/entities/auth/model/selectors';
import { Dropzone } from '@/features/Dropzone';
import { env } from '@/shared/constants';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals, SelectProps } from '@/shared/interfaces';
import { transformArrayIntoObject, validateEmail } from '@/shared/lib';
import { useKeyboard } from '@/shared/lib/hooks';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, FlexWrapper, Input, Modal, Select, Title } from '@/shared/ui';
import { ModalPage } from '@/widgets/ModalPage';
import axios from 'axios';
import cn from 'classnames';
import { useWindowSize } from 'usehooks-ts';

import s from './FeedbackModal.module.scss';

const sorts = transformArrayIntoObject(['Техническая поддержка', 'Предложения и пожелания', 'Другое']);

export const FeedbackModal = () => {
  const { closeModal, data, openModal, setData } = React.useContext(ModalContext);
  const [localEmail, setLocalEmail] = React.useState<string>(data?.localEmail ? data?.localEmail : '');
  const [isCorrectEmail, setIsCorrectEmail] = React.useState<boolean>(true);
  const [message, setMessage] = React.useState<string>(data?.message ? data?.message : '');
  const [sort, setSort] = React.useState<SelectProps | undefined>(data?.sort ? data?.sort : undefined);
  const [isChoosing, setIsChoosing] = React.useState<boolean>(false);
  const [isConfirmOpen, setIsConfirmOpen] = React.useState<boolean>(false);
  const [isLoading, setIsLoading] = React.useState<boolean>(false);
  const [isCorrectEmailShown, setIsCorrectEmailShown] = React.useState<boolean>(false);

  const { width } = useWindowSize();

  const files = useAppSelector(getFeedbackFiles);
  const dispatch = useAppDispatch();

  const handleSetLocalEmail = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    setIsCorrectEmailShown(false);
    setLocalEmail(value.replace(/\s/g, ''));
  };

  const handleSetMessage = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const { value } = event.target;
    setMessage(value);
  };

  const handleClearValues = () => {
    dispatch(clearFeedbackFiles());
    setLocalEmail('');
    setSort(undefined);
    setMessage('');
  };
  const handleSendMessage = async () => {
    const formData = new FormData();
    files?.forEach((file) => {
      formData.append('files', {
        uri: file.preview,
        type: file.type,
        name: file.name,
      } as unknown as Blob);
    });
    formData.append('theme', (sort?.title || '').trim());
    formData.append('email', localEmail.trim());
    formData.append('message', message);
    setIsLoading(true);
    try {
      const response = await axios.post(`${env.apiUrl}/user/send-feedback-unauth`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      if (response.status === 201) {
        setIsLoading(false);
        handleClearValues();
        setIsConfirmOpen(false);
        setData(() => ({ ...data, email: localEmail }));
        openModal(Modals.MessageSendModal);
        // closeModal();
      }
    } catch (error: any) {
      setIsLoading(false);
      throw new Error(error.message);
    }
  };
  const emailValidation = React.useCallback(() => {
    const isValid = validateEmail(localEmail);

    // Проверяем, есть ли совпадение в регулярном выражении
    if (isValid !== null) {
      setIsCorrectEmail(!!isValid);
    } else {
      setIsCorrectEmail(false); // Если нет совпадения, считаем email неверным
    }
  }, [localEmail]);

  React.useEffect(() => {
    if (localEmail.length > 0) {
      emailValidation();
    }
  }, [localEmail]);

  const handleGoBack = () => {
    closeModal();
    dispatch(clearEmailStatus());
  };
  const disabledCondition = !isCorrectEmail || localEmail.length === 0 || message.length === 0 || !sort?.title;

  const handleSetConfirm = () => {
    setIsConfirmOpen(true);
  };
  useKeyboard('Escape', handleGoBack);
  useKeyboard('Enter', () => {
    if (!disabledCondition) {
      handleSendMessage();
    } else {
      // eslint-disable-next-line no-console
      return console.log('Заполните все поля');
    }
  });

  React.useEffect(() => {
    if (width > 768) {
      document.body.style.overflowX = 'hidden';
    }
    return () => {
      document.body.style.overflow = 'auto';
      handleClearValues();
    };
  }, []);

  React.useEffect(() => {
    if (isChoosing) {
      document.body.style.overflow = 'hidden';
    }
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, [isChoosing]);
  React.useEffect(() => {
    if (sort) {
      setSort(sort);
    }
  }, [sort]);

  const handleClose = () => {
    setIsConfirmOpen(false);
  };

  const handleFullClose = () => {
    closeModal();
  };

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, []);

  return (
    <>
      {isChoosing && (
        <>
          <div className={s.fadedMobile}></div>
          <div className={s.choose}>
            <h4 className={s.title}>Тема</h4>
            <div className={s.closeCircleMobile} onClick={() => setIsChoosing(false)}>
              <CloseCircleMobile />
            </div>
            {sorts.map((item, index) => (
              <span
                className={index !== sorts.length - 1 ? s.chooseItem : s.chooseItemWithoutBorder}
                key={item.id}
                onClick={() => {
                  setSort(item);
                  setTimeout(() => {
                    setIsChoosing(false);
                  }, 50);
                }}
              >
                <>
                  {item.title}
                  {item.id.toString() === sort?.id.toString() && (
                    <div className={s.check}>
                      <Check />
                    </div>
                  )}
                </>
              </span>
            ))}
          </div>
        </>
      )}
      <ModalPage
        className={s.modal}
        handleClose={() => {
          if (
            ((sort?.title.length || 0) > 0 && sort?.title !== 'Выберите тему') ||
            localEmail.length > 0 ||
            message.length > 0 ||
            files.length > 0
          ) {
            handleSetConfirm();
          } else {
            closeModal();
          }
        }}
        isMobile={false}
        isOpen
      >
        <Container isModal isSmallGap isVisible={isConfirmOpen && width > 1024}>
          <TitleBlock
            handleGoBack={() => {
              if (
                ((sort?.title.length || 0) > 0 && sort?.title !== 'Выберите тему') ||
                localEmail.length > 0 ||
                message.length > 0 ||
                files.length > 0
              ) {
                handleSetConfirm();
              } else {
                closeModal();
              }
            }}
            hFourText="Написать нам"
            tg
          />
          <div className={s.sort_container}>
            <Select
              className={s.sort}
              config={{ title: sort?.title || '', values: sorts }}
              isFullWidth
              isHover={false}
              onSelect={setSort}
              selected={sorts.filter((item) => item === sort)}
              // eslint-disable-next-line no-nested-ternary
              withPlaceholder="Выберите тему"
            />
          </div>
          {width < 1024 && (
            <FlexWrapper>
              <div style={{ position: 'relative', zIndex: '1' }}>
                <Input
                  data-testid="input-topic"
                  disabled={(sort?.title.length || 0) > 0}
                  onTouchStart={() => {
                    setIsChoosing(true);
                  }}
                  placeholder="Выберите тему"
                  value={sort?.title}
                />
                <div
                  className={s.chevronLeft}
                  onClick={() => {
                    setIsChoosing(true);
                  }}
                >
                  <ChevronRight />
                </div>
              </div>
            </FlexWrapper>
          )}
          <FlexWrapper isModalWidth>
            <Input
              data-testid="input-email"
              isAutoFocus={width > 768 && localEmail.length === 0}
              isClose={localEmail.length > 0}
              isEmailField
              isNotAccepted={isCorrectEmailShown && localEmail.length !== 0}
              isNotAcceptedText="Неверный формат"
              onBlur={() => {
                if (!isCorrectEmail) {
                  setTimeout(() => {
                    setIsCorrectEmailShown(true);
                  }, 100);
                }
              }}
              onChange={handleSetLocalEmail}
              onClear={() => {
                setLocalEmail('');
                setIsCorrectEmailShown(false);
              }}
              placeholder="Почта"
              value={localEmail}
            />
          </FlexWrapper>
          <FlexWrapper isModalWidth>
            <div style={{ position: 'relative', width: '100%' }}>
              <textarea
                className={s.textarea}
                onChange={handleSetMessage}
                placeholder="Сообщение"
                value={message}
              ></textarea>
            </div>
          </FlexWrapper>
          <Dropzone isLoading={isLoading} />
          <FlexWrapper className={s.insideBlock} isCenter>
            <Button
              className={s.btn}
              disabled={disabledCondition}
              onClick={handleSendMessage}
              variant={ButtonVariants.Primary}
            >
              Отправить
            </Button>
          </FlexWrapper>
        </Container>
      </ModalPage>
      <Modal
        containerClassName={s.modal}
        handleGoBack={!disabledCondition ? handleFullClose : handleClose}
        isOpen={isConfirmOpen}
        onCloseClick={handleClose}
        withGoBack
        zIndex={3000}
      >
        {!disabledCondition ? (
          <FlexWrapper isCenter>
            <Title size="modal-size">Отправить сообщение?</Title>
            <Button
              disabled={false}
              onClick={() => {
                handleSendMessage();
              }}
              style={{ marginBottom: '24px', marginTop: '24px' }}
              variant={ButtonVariants.Primary}
            >
              Отправить
            </Button>
            <FlexWrapper className={cn(s.insideBlock)}>
              <span className={s.exit} onClick={handleClose}>
                Не отправлять
              </span>
            </FlexWrapper>
          </FlexWrapper>
        ) : (
          <FlexWrapper isCenter>
            <Title size="modal-size">Продолжить заполнение?</Title>
            <Button
              disabled={false}
              onClick={handleClose}
              style={{ marginBottom: '24px', marginTop: '24px' }}
              variant={ButtonVariants.Primary}
            >
              Продолжить
            </Button>
            <FlexWrapper className={cn(s.insideBlock)}>
              <Button className={s.exit} onClick={handleFullClose} variant={ButtonVariants.LinkDanger}>
                Выйти
              </Button>
            </FlexWrapper>
          </FlexWrapper>
        )}
      </Modal>
    </>
  );
};
